package com.tarena.service;

import com.google.gson.Gson;
import com.tarena.pojo.Message;
import com.tarena.pojo.MessageType;
import com.tarena.pojo.User;


import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class ServerSocketThread extends Thread {
    private Socket socket;
    private User user;
    private Gson gson = new Gson();
    private OutputStream out;
    private ObjectOutputStream oos;
    private InputStream in;
    private ObjectInputStream ois;

    public ServerSocketThread(Socket socket, User user) {
        try {
            this.socket = socket;
            this.user=user;
            out = socket.getOutputStream();
            oos = new ObjectOutputStream(out);
            in = socket.getInputStream();
            ois = new ObjectInputStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //this.user = user;
    }

    public void sendMsg(Message message){
        try {
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public Socket getSocket() {
        return socket;
    }

    public Set<User> getUserData(HashMap<String,User> userData){
        Set<User> users = new HashSet<>();
        Collection<User> values = userData.values();
        for (User value : values) {
            users.add(value);
        }
        return users;

    }

    public void reFriendsList(String msgType){
        Set<User> users=null;
        try {
            /*构建message对象*/
            Message message = new Message();
            if(msgType.equals(MessageType.MESSAGE_RET_ONLINE_FRIENDS)){
                /*返回给客户端对应的好列表*/
                users =ManageConnectServerList.getAllonlineUser();
                /*把users放入到messages对象的content属性*/
                message.setMagType(MessageType.MESSAGE_RET_ONLINE_FRIENDS);
            }else{
//                返回给客户端所有好友的列表
                users = getUserData(ChatServer.userData);
                /*把users放入到messages对象的content属性*/
                message.setMagType(MessageType.MESSAGE_RET_ALL_FRIENDS);

            }
            //将uesrs转换为json对象；
            String userJson = gson.toJson(users);
            message.setContent(userJson);
            /*使用输出流写出对象到客户端*/
            oos.writeObject(message);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {/*线程处于run的状态，即可发生消息*/

        while(true){
            System.out.println("服务端已和客户端："+user.getUsername()+"保持通讯！");
            try {
               /* InputStream in = socket.getInputStream();
                ObjectInputStream ois = new ObjectInputStream(in);*/
                /*如果服务器没有给客户端发送Message对象，线程会一直阻塞（）*/
                Message message = (Message) ois.readObject();
                /*message中的消息以后处理*/
                /*一旦获取到message对象，不是服务端接受了对应的客户端的请求*/
                if(message.getMagType().equals(MessageType.MESSAGE_GET_ONLINE_FRIENDS)) {
                    reFriendsList(MessageType.MESSAGE_RET_ONLINE_FRIENDS);
                }

                if(message.getMagType().equals(MessageType.MESSAGE_GET_ALL_FRIENDS)) {
                    reFriendsList(MessageType.MESSAGE_RET_ALL_FRIENDS);
                }
                /*获取单聊信息*/
                if(message.getMagType().equals(MessageType.MESSAGE_COMM_MES)) {
                    //System.out.println(message.getContent());
                    ManageConnectServerList.sendMsgToUser(message);
                }

            }catch(SocketException e){
                /*服务器线程感知到客户端线程异常断开*/
                /*1.从hashmap中将对应的客户端，删除掉*/
                ManageConnectServerList.removeThreadFromMap(user);
                /*2.重新刷新用户列表*/
                ManageConnectServerList.notiClientRefFriends(null);
                try {
                    socket.close();
                } catch (IOException ioException) {
                    ioException.printStackTrace();
                }
                break;

            } catch (IOException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
